import subprocess, re, logging, time

def list_online_devices():
    """返回 ['SN1','SN2', ...]；忽略离线设备"""
    try:
        out = subprocess.check_output(["adb", "devices"], text=True, timeout=10)
        devs = []
        for line in out.splitlines():
            if line.endswith("\tdevice"):
                devs.append(line.split('\t')[0])
        if not devs:
            logging.warning("⚠️ adb devices 列表为空！")
        return devs
    except subprocess.TimeoutExpired:
        logging.error("adb devices 命令超时")
        return []
    except Exception as e:
        logging.error(f"获取设备列表失败: {e}")
        return []

def sanitize_sn(sn: str) -> str:
    """防止目录中出现冒号，ip:port -> ip_port"""
    return re.sub(r'[:/\\]', '_', sn)

def verify_device_connection(sn: str, max_retries=3) -> bool:
    """验证设备是否真正连接可用"""
    for attempt in range(max_retries):
        try:
            # 检查设备是否在列表中
            devices = list_online_devices()
            if sn not in devices:
                logging.warning(f"设备 {sn} 不在在线设备列表中")
                if attempt < max_retries - 1:
                    time.sleep(2)
                    continue
                return False
            
            # 尝试执行简单命令验证设备响应
            result = subprocess.run(
                ["adb", "-s", sn, "shell", "echo", "test"], 
                capture_output=True, 
                text=True, 
                timeout=10
            )
            
            if result.returncode == 0:
                return True
            else:
                logging.warning(f"设备 {sn} 响应异常，返回码: {result.returncode}")
                
        except subprocess.TimeoutExpired:
            logging.warning(f"设备 {sn} 响应超时 (尝试 {attempt + 1}/{max_retries})")
        except Exception as e:
            logging.error(f"验证设备 {sn} 连接时出错: {e}")
        
        if attempt < max_retries - 1:
            time.sleep(2)
    
    return False

def filter_available_devices(device_list: list[str]) -> list[str]:
    """过滤出真正可用的设备列表"""
    available_devices = []
    
    for sn in device_list:
        if verify_device_connection(sn):
            available_devices.append(sn)
        else:
            logging.warning(f"设备 {sn} 不可用，已跳过")
    
    if not available_devices:
        logging.error("没有可用的设备")
    
    return available_devices
